package com.wxtf.platform.main.contraceptives;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;
/**
 * <li>Title: TmaOutcomeAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.main.contraceptives</li>
 * <li>Description: 药具出库</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Jul 5, 2012 10:08:48 AM</li>
 *
 * @author liu_zhaojun
 * @version 1.0.0.0
 *
 */
public class TmaOutcomeAction extends LogicBase implements CommonsCallProvider  {

	private static Log log = LogFactory.getLog(TmaOutcomeAction.class);

	public TmaOutcomeAction(String jsonArray) {

	}
	
	/** 
	 * 描述：delete 删除出库记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		String sql = "delete from tma_outcome_main where tmaom_id = ?";
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	/** 
	 * 描述：insert 增加出库记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	@Override
	public Object insert(Object jsonArray) throws Exception {		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String org_id = user.getCurOrgId();
		String subOrg_id = jsonObject.getString("org_id");
		String tmaom_code = jsonObject.getString("tmaom_code");
		sql = "select count(*) from tma_outcome_main where tmaom_code=?";
		List<Object> ls = AccessDataBaseUtil.query4List(sql,new Object[]{tmaom_code});
		int hasId = Integer.parseInt(ls.get(0).toString());
		if(hasId>0){
			return "\"出库编号不能重复\"";
		}
		String create_time = FormatUtil.getCurentDate();				
		String tmaom_id = AccessDataBaseUtil.getPKUUID();
		String create_by = user.getUserId();
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer("insert into tma_outcome_main(tmaom_id,org_id,tmaom_type,tmaom_is_valid,tmaom_code,tmaom_time,create_by,create_time,last_modify_by,last_modify_time) values(");
		buff.append("'").append(tmaom_id).append("'")
		.append(",'").append(org_id).append("'")
		.append(",'").append(jsonObject.getString("tmaom_type")).append("'")
		.append(",'").append(jsonObject.getString("tmaom_is_valid")).append("'")
		.append(",'").append(tmaom_code).append("'")
		.append(",'").append(jsonObject.getString("tmaom_time")).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("')");
		list.add(buff.toString());
		buff.setLength(0);
		String ids = jsonObject.getString("ids");
		array = JSONArray.fromObject(ids);
		for(int i=0;i<array.size();i++){
			jsonObject = array.getJSONObject(i);
			buff.append("insert into tma_outcome_detail(tmaod_id,tmaom_id,tmad_id,tmaod_num,create_by,create_time,last_modify_by,last_modify_time) values(")
			.append("'").append(AccessDataBaseUtil.getPKUUID()).append("'")
			.append(",'").append(tmaom_id).append("'")
			.append(",'").append(jsonObject.getString("tmad_id")).append("'")
			.append(",'").append(jsonObject.getString("tmaod_num")).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("')");
			list.add(buff.toString());
			buff.setLength(0);
		}
		if(org_id.equals(subOrg_id)){
			
		}else{
			//入库
			String tmaim_code = "";
			String time = tmaom_code.substring(0, tmaom_code.length() - 5);
			String rukubianhao = "00001";
			boolean bool = true;
			while(bool){
				tmaim_code = time + rukubianhao;
				sql = "select count(*) from TMA_INCOME_MAIN where tmaim_code=?";
				int Id = AccessDataBaseUtil.queryForInt(sql,new Object[]{tmaim_code});
				if(Id==0){
					break;
				}
				int i = Integer.valueOf(rukubianhao);
				i++;
				String s = "";
				int a = rukubianhao.length();
				int b = Integer.toString(i).length();
				while(a - b > 0){
					s += "0";
					a--;
				}
				rukubianhao = s + i;
			}
			String tmaim_id = AccessDataBaseUtil.getPKUUID();
			buff = new StringBuffer("insert into TMA_INCOME_MAIN(tmaim_id,org_id,tmaim_type,tmaim_is_valid,tmaim_code,tmaim_time,create_by,create_time,last_modify_by,last_modify_time) values(");
			buff.append("'").append(tmaim_id).append("'")
			.append(",'").append(subOrg_id).append("'")
			.append(",'").append("1").append("'")
			.append(",'").append("1").append("'")
			.append(",'").append(tmaim_code).append("'")
			.append(",'").append(create_time).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("')");
			list.add(buff.toString());
			buff.setLength(0);
			array = JSONArray.fromObject(ids);
			for(int i=0;i<array.size();i++){
				jsonObject = array.getJSONObject(i);
				buff.append("insert into TMA_INCOME_DETAIL(tmaid_id,tmaim_id,tmad_id,tmaid_num,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("'")
				.append(",'").append(tmaim_id).append("'")
				.append(",'").append(jsonObject.getString("tmad_id")).append("'")
				.append(",'").append(jsonObject.getString("tmaod_num")).append("'")
				.append(",'").append(create_by).append("'")
				.append(",'").append(create_time).append("'")
				.append(",'").append(create_by).append("'")
				.append(",'").append(create_time).append("')");
				list.add(buff.toString());
				buff.setLength(0);
			}
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"新建成功\"";
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getLogicData());
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else if ("detail".equals(this.getMethodName())) {// 删除
				msg = this.detail(this.getLogicData());
			} else if ("selectTmaNumById".equals(this.getMethodName())) {// 删除
				msg = this.selectTmaNumById(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")){
				return msg;
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}
	/** 
	 * 描述：select 查询出库主表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String org_id = user.getCurOrgId();
		sql = " from tma_outcome_main a,t_department b,t_user c where a.org_id=b.department_id and a.create_by=c.user_id and a.org_id= '"+org_id+"'";
		String countSql = "select count(*) " + sql;
		String querySql = "select s.id,s.org_id,s.code,s.time,s.tmaotpye,s.create_by,s.isvalid,n.caption from (select a.tmaom_id as id,b.caption as org_id,a.tmaom_code as code,a.tmaom_time as time,(case when a.tmaom_type='2' then '使用报废' when a.tmaom_type='3' then '库存报废' when a.tmaom_type='4' then '过期报废' else '出库' end) as tmaotpye,c.caption as create_by,a.tmaom_is_valid as isvalid" + sql + ") s left join tma_apply_main m on s.id=m.tmaam_id left join t_department n on m.org_id=n.department_id ";
		String[] fields = {"tmaom_id","org_id","tmaom_code","tmaom_time","tmaom_type","create_by","tmaom_is_valid","org_id2"};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}
	
	/** 
	 * 描述：detail 查询出库明细表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object detail(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmaom_id = jsonObject.getString("tmaom_id");
		sql = " from TMA_DICTIONARY t inner join tma_outcome_detail d on t.tmad_id=d.tmad_id and d.tmaom_id=? left join tm_general_dictionary g on t.tmad_kind=g.tmgd_id";
		String querySql = "select t.tmad_name,g.tmgd_name,t.tmad_company_name,t.tmad_price,d.tmaod_num" + sql;
		String[] fields = {"tmad_name","tmgd_name","tmad_company_name","tmad_price","tmaod_num"};
		array = JSONArray.fromObject(AccessDataBaseUtil.query(fields, querySql, new Object[]{tmaom_id}));
		return "{\"Rows\":" + array.toString() + "}";
	}
	
	/** 
	 * 描述：selectTmaNumById 根据Id查询
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object selectTmaNumById(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String org_id = user.getCurOrgId();
		String tmad_id = jsonObject.getString("tmad_id");
		StringBuffer buff = new StringBuffer("select (sum(kc.num)-(case when kl.num_s is null then 0 else kl.num_s end)) as num");
		buff.append(" from tma_dictionary a inner join tm_general_dictionary b on a.tmad_kind=b.tmgd_id and b.tmgd_type='105' and a.tmad_id='").append(tmad_id).append("'")
		.append(" left join kucun kc on a.tmad_id=kc.id")
		.append(" left join (select k.tmad_id as id,sum(k.tmaod_num) as num_s from tma_outcome_detail k inner join tma_outcome_main l on k.tmaom_id=l.tmaom_id and l.tmaom_type in ('2','3','4') and l.tmaom_is_valid='1' group by k.tmad_id) kl on kc.id = kl.id")
		.append(" where kc.orgid='").append(org_id).append("'");
		List<Object> list = AccessDataBaseUtil.query4List(buff.toString(), null);
		int num = 0;
		if(list!=null&&list.size()>0){
			if(!"".equals(list.get(0))){
				num = Double.valueOf(list.get(0).toString()).intValue();
			}			
		}		
		return num;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

}
